
(function ($) {
  var
    $window = $(window),
    $body = $(document.body),
    $wrapper = $('#pageWrapper');

  var templates = {
    pgauth : 'template-page-auth',
    pgsearch : '',
    pgdefault : 'template-page-dashboard',
    pgexception : '',
    pgdashboard : 'template-page-dashboard',
    pgtasklists : 'template-page-tasklists',
    pgtasklist : 'template-page-tasklists-item',
    pgtask : 'template-page-task',
    pgdiscussions : 'template-page-discussions',
    pgdiscussion : 'template-page-discussions-item'
  };

  Teamlab.bind(Teamlab.events.addComment, onAddComment);
  Teamlab.bind(Teamlab.events.updateComment, onUpdateComment);

  Teamlab.bind(Teamlab.events.changePage, onChangePage);

  Teamlab.bind(Teamlab.events.authPage, onAuthPage);

  Teamlab.bind(Teamlab.events.dashboardPage, onDashboardPage);

  Teamlab.bind(Teamlab.events.taskPage, onTaskPage);
  Teamlab.bind(Teamlab.events.tasklistPage, onTasklistPage);
  Teamlab.bind(Teamlab.events.tasklistsPage, onTasklistsPage);
  Teamlab.bind(Teamlab.events.tasklistsLoadTasks, onTasklistsLoadTasks);

  Teamlab.bind(Teamlab.events.discussionsPage, onDiscussionsPage);
  Teamlab.bind(Teamlab.events.discussionPage, onDiscussionPage);
  Teamlab.bind(Teamlab.events.discussionsLoadDiscussions, onDiscussionsLoadDiscussions);

  function loadTemplate (src, template) {
    var xhr = null;
    if (window.XMLHttpRequest) {
      xhr = new XMLHttpRequest();
    }

    if (!xhr) {
      return undefined;
    }

    //xhr.onreadystatechange = (function (xhr) {
    //  return function () {
    //    if (xhr.readyState === 4) {
    //      if (xhr.status === 200 || xhr.status === 201 || xhr.status === 202) {
    //        //TODO:
    //      }
    //    }
    //    delete xhr;
    //  };
    //})(xhr);
    xhr.onreadystatechange = function () {};
    xhr.open('GET', src, false);
    xhr.send(null);

    if (xhr.readyState === 4) {
      if (xhr.status === 200 || xhr.status === 201 || xhr.status === 202) {
        template.innerHTML = xhr.responseText;
      }
    }

    delete xhr.onreadystatechange;
    xhr.onreadystatechange = null;
    delete xhr;
    xhr = null
  }

  window.prepareTemplates = function () {
    var
      src = null,
      template = null,
      $templates = $('script[type="text/x-jquery-tmpl"]'),
      temlatesInd = $templates.length;
    while (temlatesInd--) {
      template = $templates[temlatesInd];
      src = template.getAttribute('src');
      if (typeof src === 'string' && src.length > 0) {
        loadTemplate(src, template);
      }
    }
  };

  function processTemplate (templid, data) {
    var timestamp = new Date().getTime();
    var $item = $('#' + templid).tmpl(data);
    console._log.push('processTemplate: ' + templid + ' - ' + (new Date().getTime() - timestamp) + 'ms');
    $window.trigger('render-template', [$item]);
    return $item;
  }

  function renderPageByTemplate (templid, pageid, data) {
    var $page = $();
    if (pageid) {
      $page = $wrapper.children('div.ui-page').filter('[data-pageid="' + pageid + '"]:first');
    }
    if ($page.length > 0) {
      switch (templid) {
        case '' :
          return $page;
      }
      $page.remove();
    }

    try {
      $page = processTemplate(templid, data).appendTo($wrapper)
    } catch (err) {
      console.log(err);
      console.trace();
      $page = $();
    }

    if (pageid) {
      $page.attr('data-pageid', pageid);
    }

    if (data.hasOwnProperty('id')) {
      $page.attr('data-itemid', data.id);
    }

    return $page;
  }

  function renderPage (pgtype, pgid, data) {
    var pgtmpl = '';

    switch (pgtype.toLowerCase()) {
      case 'page-auth' : pgtmpl = templates.pgauth; pgid = 'pgauth-' + pgid; break;
      case 'page-index' :pgtmpl = templates.pgdefault; pgid = 'pgdef-' + pgid; break;
      case 'page-search' : pgtmpl = templates.pgsearch; pgid = 'pgsch-' + pgid; break;
      case 'page-exception' : pgtmpl = templates.pgexception; pgid = 'pgexc-' + pgid; break;
      case 'page-dashboard' : pgtmpl = templates.pgdashboard; pgid = 'pgdhd-' + pgid; break;
      case 'page-tasklists' : pgtmpl = templates.pgtasklists; pgid = 'pgtls-' + pgid; break;
      case 'page-tasklist' : pgtmpl = templates.pgtasklist; pgid = 'pgtls-item-' + pgid; break;
      case 'page-task' : pgtmpl = templates.pgtask; pgid = 'pgtls-tsk-' + pgid; break;
      case 'page-discussions' : pgtmpl = templates.pgdiscussions; pgid = 'pgdsn-' + pgid; break;
      case 'page-discussion' : pgtmpl = templates.pgdiscussion; pgid = 'pgdsn-item-' + pgid; break;
      default :
        return $();
    }

    $body.removeClass('dialog-mode').addClass('page-mode');
    $window.trigger('startrender-page', []);
    var $page = renderPageByTemplate(pgtmpl, pgid, data || {});
    $page.addClass('active');
    $wrapper.children('div.ui-page.active').not($page).removeClass('active');
    $window.trigger('endrender-page', [$page, pgtype.toLowerCase()]);
    return $page;
  }

  function onAddComment (params, data) {
    data = {type : data.type, id : data.id, parentid : data.parentid, item : data.item};
    var $comment = processTemplate('template-gnrl-comments', data);
    $window.trigger('render-new-comment', [data.type, data.item.parentid, $comment]);
  }

  function onUpdateComment (params, data) {
    data = {type : data.type, id : data.id, parentid : data.parentid, item : data.item};
    var $comment = processTemplate('template-gnrl-comments', data);
    $window.trigger('render-update-comment', [data.type, data.item.id, $comment]);
  }

  function onChangePage () {
    $window.trigger('change-page', []);
  }

  function onAuthPage (params, data) {
    data = {};
    data.pagetitle = 'Auth';
    renderPage('page-auth', 'auth', data);
  }

  function onDashboardPage (params, data) {
    data = {pagemenu : data.pagemenu};
    data.pagetitle = 'Dashboard';
    renderPage('page-dashboard', 'dashboard', data);
  }

  function onTasklistsPage (params, data) {
    data = {pagemenu : data.pagemenu, items : data.items, classname : 'collection-tasklists', subclassname : 'sub-collection-tasks'};
    data.pagetitle = 'Tasklists';
    renderPage('page-tasklists', 'tasklists', data);
  }

  function onTasklistPage (params, data) {
    data = {pagemenu : data.pagemenu, items : data.items};
    data.pagetitle = data.items[0].projecttitle;
    renderPage('page-tasklist', 'tasklists', data);
  }

  function onTaskPage (params, data) {
    data = {pagemenu : data.pagemenu, item : data.item};
    data.pagetitle = data.item.projecttitle + ' ' + data.item.title;
    renderPage('page-task', 'tasklists', data);
  }

  function onTasklistsLoadTasks (params, data) {
    data = {items : data.items, classname : 'sub-collection-tasks'};
    var $tasklist = processTemplate('template-gnrl-sub-collection', data);
    $window.trigger('render-tasklists-project-tasks', [$tasklist]);
  }

  function onDiscussionsPage (params, data) {
    data = {pagemenu : data.pagemenu, items : data.items, classname : 'collection-discussions', subclassname : 'sub-collection-discussions'};
    data.pagetitle = 'Discussions';
    renderPage('page-discussions', 'discussions', data);
  }

  function onDiscussionsLoadDiscussions (params, data) {
    data = {items : data.items, classname : 'sub-collection-discussions'};
    var $discussions = processTemplate('template-gnrl-sub-collection', data);
    $window.trigger('render-discussions-project-discussions', [$discussions]);
  }

  function onDiscussionPage (params, data) {
    data = {pagemenu : data.pagemenu, id : data.id, items : data.items, classname : 'discussion-discussion-item'};
    data.pagetitle = 'Discussions';
    renderPage('page-discussion', 'discussions', data);
  }
})(jQuery);
